package com.youkeda.test.netty.server;

import com.youkeda.test.netty.handler.ServerChannelHandlerSimple;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class NettyServerListenerSimple {


    /**
     * 创建bootstrap
     */
    private static final ServerBootstrap serverBootstrap = new ServerBootstrap();

    /**
     * Worker
     */
    private static final EventLoopGroup work = new NioEventLoopGroup();

    /**
     * 端口号
     */
    private int port = getPort();

    /**
     * 关闭服务器方法
     */
    public void close() {
        System.out.println("关闭服务器....");
        //优雅退出
        work.shutdownGracefully();
    }

    /**
     * 开启及服务线程
     */
    public void start() {
        serverBootstrap.group(work)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.INFO));
        try {
            //设置事件处理
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new ServerChannelHandlerSimple());
                }
            });
            System.out.println("Netty服务器在[" + port + "]端口启动监听");
            ChannelFuture f = serverBootstrap.bind(port);
            f.channel().closeFuture();
        } catch (Exception e) {
            System.out.println("[出现异常] 释放资源");
        } finally {
            close();
        }
    }

    private static int getPort() {
        Double port = (Math.random() + 1) * 10000;
        return port.intValue();
    }

    public static void main(String[] args) {
        NettyServerListenerSimple nsl = new NettyServerListenerSimple();
        nsl.start();
    }
}
